// 创建用户相关的小仓库
import { defineStore } from 'pinia'
// 引入接口
// 引入数据类型
import type { UserState } from './types/type'
import {
  getLoginUser,
  userLogin,
  userLogout,
} from '@/api/front/user/userController'
// 引入路由
import { constantRoute } from '@/router/routes'

// 定义一个过滤异步数组的方法
function filterAsyncRoute(asyncRoute: any, routes: any) {
  return asyncRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}

// 创建用户小仓库
const useUserStore = defineStore('User', {
  // 存储数据的地方
  state: (): UserState => {
    return {
      token: localStorage.getItem('TOKEN'),
      userAvatar: '',
      nickname: '',
      id: '',
      buttons: [],
      permissions: [],
      showDialog: false, // 用于控制登录对话框的显示状态
      menuRoutes: constantRoute, // 用户菜单路由数据
    }
  },
  // 处理异步|逻辑的地方
  actions: {
    // 用户登录的方法
    async userLogin(data: API.UserLoginRequestDTO) {
      const result = await userLogin(data)
      if (result.data.code === '0') {
        // 存储token
        this.token = result.data.data?.token as string
        this.userAvatar = result.data.data?.userAvatar as string
        this.nickname = result.data.data?.nickname as string
        // this.permissions = result.data.permission as string[]
        // 本地存一份
        localStorage.setItem('TOKEN', result.data.data?.token as string)
        return 'ok'
      } else {
        return Promise.reject(new Error(result.data.message))
      }
    },
    // 获取用户信息的方法
    async userInfo() {
      const result = await getLoginUser()
      if (result.data.code === '0') {
        this.userAvatar = result.data.data?.userAvatar || ''
        this.nickname = result.data.data?.nickname || '无名'
        // 设置用户路由 - 确保首页路由和后台管理页面显示在菜单中
        this.menuRoutes = constantRoute.filter(
          (route) =>
            !route.meta?.hidden ||
            route.name === '后台首页' ||
            route.name === 'Dashboard',
        )
        return 'ok'
      } else {
        return Promise.reject('获取用户信息失败')
      }
    },
    // 退出登录的方法
    async userLogout() {
      const result = await userLogout()
      if (result.data.code === '0') {
        this.token = ''
        this.userAvatar = ''
        this.nickname = ''
        localStorage.removeItem('TOKEN')
        localStorage.removeItem('User')
        return 'ok'
      } else {
        return Promise.reject('退出失败')
      }
    },
  },
  persist: true,
})
//参数持久化

export default useUserStore
